package com.weslide.weslideapp.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.gt.cl.http.CLConnectionException;
import com.gt.cl.http.CLInvalidNetworkException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.weslide.weslideapp.R;
import com.weslide.weslideapp.activity.CityListActivity;
import com.weslide.weslideapp.activity.GiftDetailActivity;
import com.weslide.weslideapp.manager.api.APIManager;
import com.weslide.weslideapp.manager.api.LoginManager;
import com.weslide.weslideapp.pojo.ao.GiftAO;
import com.weslide.weslideapp.pojo.ao.GiftListAO;
import com.weslide.weslideapp.pojo.ao.LoginAO;
import com.weslide.weslideapp.pojo.ao.ZoneAO;
import com.weslide.weslideapp.util.TMTPAsyncTask;

public class ScoreStoreFragment extends WeSlideFragment {
	public final static String TAG = "ScoreStoreFragment";
	private ListView mLvGoodsList;
	private String currentTypeId = "-1";
	private TextView mTvTitle;
	private RadioButton mRdo1;
	private RadioButton mRdo2;
	private RadioButton mRdo3;
	private RadioGroup mRdGSift;
	private TMTPAsyncTask<Void, Void, Void> asyncTask;
	private GiftListAO gifts;
	private List<GiftAO> giftList = new ArrayList<GiftAO>();
	public static final int REQUEST_CODE_SELECT_CITY = 123;
	private DisplayImageOptions options;
	private String mCurrent = "－1";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, "onCreateView");
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.a5)
				.showImageForEmptyUri(R.drawable.a5)
				.showImageOnFail(R.drawable.a5).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888).build();
		globalView = inflater.inflate(R.layout.page_score_store, container,
				false);
		findViews();
		init();
		fetchListById(currentTypeId);
		return globalView;
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.i(TAG, "onCreateView");
	}

	private void findViews() {
		mTvTitle = (TextView) findViewById(R.id.page_score_store_mTvTitle);
		mLvGoodsList = (ListView) findViewById(R.id.page_score_store_mLvGoodsList);
		findViewById(R.id.page_score_store_mImgVCategory).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						getMainActivity().move();
					}
				});
		mTvTitle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						CityListActivity.class);
				startActivityForResult(intent, REQUEST_CODE_SELECT_CITY);
			}
		});
		mRdGSift = (RadioGroup) findViewById(R.id.page_score_store_mRdGSift);
		mRdGSift.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.page_score_store_mRdo1:
					mCurrent = "5000";
					fetchListById(currentTypeId);
					break;

				case R.id.page_score_store_mRdo2:
					mCurrent = "10000";
					fetchListById(currentTypeId);
					break;

				case R.id.page_score_store_mRdo3:
					mCurrent = "100000";
					fetchListById(currentTypeId);
					break;

				}
			}
		});
	}

	public void fetchListById(String typeId) {
		Log.i(TAG, "typeId >>> " + typeId);
		currentTypeId = typeId;
		asyncTask = new TMTPAsyncTask<Void, Void, Void>(getActivity()) {

			@Override
			protected void doOnSuccess(Void result) {
				giftList.clear();
				giftList.addAll(gifts.getGiftList());

				myAdapter.notifyDataSetChanged();
			}

			@Override
			protected Void doInBackground(Void params)
					throws CLInvalidNetworkException, CLConnectionException {
				// LoginAO loginAO = LoginManager.getInstance()
				// .getUserInformation();

				try {
					ZoneAO currentCity = LoginManager.getInstance()
							.getCurrentCity();
					LoginAO userInformation = LoginManager.getInstance()
							.getUserInformation();
					gifts = APIManager.getInstance().getGifts(
							userInformation.getUserId(),
							currentCity.getZoneId(), currentTypeId, mCurrent);
					Log.i(TAG, "UserId >>> " + userInformation.getUserId());
					Log.i(TAG, "score >>> " + userInformation.getScore());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return null;
			}
		};
		asyncTask.execute();
	}

	private void init() {

		View header = getActivity().getLayoutInflater().inflate(
				R.layout.view_goods_list_header, null);
		mLvGoodsList.addHeaderView(header, null, false);
		mLvGoodsList.setAdapter(myAdapter);
		mLvGoodsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i(TAG, "position >>> " + position);

				GiftAO giftAO = (GiftAO) parent.getItemAtPosition(position);
				Log.i(TAG, "Name >>> " + giftAO.getName());
				Intent intent = new Intent(getActivity(),
						GiftDetailActivity.class);
				intent.putExtra(GiftDetailActivity.EXTRA_GOODID,
						giftAO.getGoodId());
				startActivity(intent);
			}
		});
	}

	private BaseAdapter myAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewholder = null;
			if (convertView == null) {
				viewholder = new ViewHolder();
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.item_goods, null);
				viewholder.image = (ImageView) convertView
						.findViewById(R.id.item_goods_mImgV);
				viewholder.goodsName = (TextView) convertView
						.findViewById(R.id.item_goods_mTvGoodsName);
				viewholder.scorePrice = (TextView) convertView
						.findViewById(R.id.item_goods_mTvGoodsScorePrice);
				viewholder.price = (TextView) convertView
						.findViewById(R.id.item_goods_mTvGoodsPrice);
				viewholder.description = (TextView) convertView
						.findViewById(R.id.item_goods_mTvDescription);
				convertView.setTag(viewholder);
			} else {
				viewholder = (ViewHolder) convertView.getTag();
			}

			GiftAO giftAO = giftList.get(position);
			if (viewholder == null) {
				Log.i(TAG, "null >>>>>>>>>>>");
			}
			viewholder.goodsName.setText(giftAO.getName());
			viewholder.scorePrice.setText(giftAO.getNeedScore() + "积分");
			viewholder.price.setText("价值" + giftAO.getMoney() + "元");
			ImageLoader.getInstance().displayImage(giftAO.getImgUrl(),
					viewholder.image, options);
			int remainder = Integer.parseInt(giftAO.getTcount())
					- Integer.parseInt(giftAO.getOcount());
			viewholder.description.setText(giftAO.getOcount() + "人已兑换，剩余"
					+ remainder + "份");
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return giftList.get(position);
		}

		@Override
		public int getCount() {
			Log.i(TAG, "size >>> " + giftList.size());
			return giftList.size();
		}
	};

	private class ViewHolder {
		ImageView image;
		TextView goodsName;
		TextView scorePrice;
		TextView price;
		TextView description;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		ZoneAO currentCity = LoginManager.getInstance().getCurrentCity();
		mTvTitle.setText("我的兑换(" + currentCity.getName() + ")");
		fetchListById(currentTypeId);
	}
}
